/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.mallsite.modules.shop.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.utils.UserUtils;
import com.mallsite.modules.shop.entity.GoodsCategory;
import com.mallsite.modules.shop.service.GoodsCategoryService;

/**
 * 商品分类Controller
 * @author ruyang
 * @version 2020-12-04
 */
@Controller
@RequestMapping(value = "${adminPath}/shop/goodsCategory")
public class GoodsCategoryController extends BaseController {

	@Autowired
	private GoodsCategoryService goodsCategoryService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public GoodsCategory get(String categoryCode, boolean isNewRecord) {
		return goodsCategoryService.get(categoryCode, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("shop:goodsCategory:view")
	@RequestMapping(value = {"list", ""})
	public String list(GoodsCategory goodsCategory, Model model) {
		model.addAttribute("goodsCategory", goodsCategory);
		model.addAttribute("user", UserUtils.getUser());
		return "modules/shop/goodsCategoryList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("shop:goodsCategory:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<GoodsCategory> listData(GoodsCategory goodsCategory) {
		if (StringUtils.isBlank(goodsCategory.getParentCode())) {
			goodsCategory.setParentCode(GoodsCategory.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(goodsCategory.getCategoryCode())){
			goodsCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(goodsCategory.getCategoryName())){
			goodsCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(goodsCategory.getCategoryRecommend())){
			goodsCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(goodsCategory.getStatus())){
			goodsCategory.setParentCode(null);
		}
		
		List<GoodsCategory> list = goodsCategoryService.findList(goodsCategory);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("shop:goodsCategory:view")
	@RequestMapping(value = "form")
	public String form(GoodsCategory goodsCategory, Model model) {
		// 创建并初始化下一个节点信息
		goodsCategory = createNextNode(goodsCategory);
		model.addAttribute("goodsCategory", goodsCategory);
		model.addAttribute("user", UserUtils.getUser());
		return "modules/shop/goodsCategoryForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("shop:goodsCategory:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public GoodsCategory createNextNode(GoodsCategory goodsCategory) {
		if (StringUtils.isNotBlank(goodsCategory.getParentCode())){
			goodsCategory.setParent(goodsCategoryService.get(goodsCategory.getParentCode()));
		}
		if (goodsCategory.getIsNewRecord()) {
			GoodsCategory where = new GoodsCategory();
			where.setShopId(goodsCategory.getShopId());
			where.setParentCode(goodsCategory.getParentCode());
			GoodsCategory last = goodsCategoryService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				goodsCategory.setTreeSort(last.getTreeSort() + 30);
				goodsCategory.setCategoryCode(IdGen.nextCode(last.getCategoryCode()));
			}else if (goodsCategory.getParent() != null){
				goodsCategory.setCategoryCode(goodsCategory.getParent().getCategoryCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (goodsCategory.getTreeSort() == null){
			goodsCategory.setTreeSort(GoodsCategory.DEFAULT_TREE_SORT);
		}
		return goodsCategory;
	}

	/**
	 * 保存商品分类
	 */
	@RequiresPermissions("shop:goodsCategory:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated GoodsCategory goodsCategory) {
		goodsCategoryService.save(goodsCategory);
		return renderResult(Global.TRUE, text("保存商品分类成功！"));
	}
	
	/**
	 * 删除商品分类
	 */
	@RequiresPermissions("shop:goodsCategory:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(GoodsCategory goodsCategory) {
		goodsCategoryService.delete(goodsCategory);
		return renderResult(Global.TRUE, text("删除商品分类成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("shop:goodsCategory:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(GoodsCategory goodsCategory, String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<GoodsCategory> list = goodsCategoryService.findList(goodsCategory);
		for (int i=0; i<list.size(); i++){
			GoodsCategory e = list.get(i);
			// 过滤非正常的数据
			if (!GoodsCategory.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getCategoryCode(), e.getCategoryName()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("shop:goodsCategory:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(GoodsCategory goodsCategory){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		goodsCategoryService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}